package com.th.cash.th2.set

import androidx.activity.viewModels
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.lxj.xpopup.XPopup
import com.th.basemodel.base.BaseVB2Activity2
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.gotoActivity
import com.th.basemodel.utils.AppUtil
import com.th.resmodel.R
import com.th.resmodel.databinding.ActivitySetBinding
import com.th.cash.th2.main.MainActivity
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

//设置页
class SetActivity : BaseVB2Activity2<ActivitySetBinding>() {

    private val mViewModel by viewModels<SetViewModel>()

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    override fun setWindowPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun init() {
        initTitle()
        initClick()
        observeState()

        mBinding.tvAppVersion.text = AppUtil.getVersionName()

        val options = RequestOptions.bitmapTransform(RoundedCorners(60))
        Glide.with(this)
            .load(R.mipmap.img_0)
            .apply(options)
            .into(mBinding.ivAppIcon)
    }

    private fun initTitle() {
        mBinding.header.headTitle.text = ""
    }

    private fun observeState() {
        lifecycleScope.launch {
            mViewModel.uiState.collectLatest { state ->
                when (state) {
                    is SetState.LogoutSuccess -> {
                        gotoActivity<MainActivity>()
                    }

                    else -> {}
                }
            }
        }
    }

    private fun initClick() {
        mBinding.header.headBack.setOnClickListener {
            finish()
        }

        mBinding.tvSubmit1.setOnClickListener {
            showLogoutPopup(0)
        }
        mBinding.tvSubmit2.setOnClickListener {
            showLogoutPopup(1)
        }
    }

    private fun showLogoutPopup(type: Int) {
        XPopup.Builder(this)
            .asCustom(
                UserExitPopup(
                    this,
                    type
                ).run {
                    clickListener = { bool ->
                        if (bool) {
                            mViewModel.intentChannel.trySend(SetIntent.Logout)
                        }
                    }
                    this
                })
            .show()
    }
} 